//
//  TopicDetailViewController.m
//  ZITHER
//
//  Created by 吴凡 on 2019/2/15.
//  Copyright © 2019 weixn. All rights reserved.
//

#import "TopicDetailViewController.h"
#import "TopicDetaillHeadImageView.h"
#import "TopicDetaillHeadInfoView.h"
#import "TopicDetailUgcTableView.h"
#import "CRBBoxHomeHttp.h"
#import "TopicDetailModel.h"
#import "Ugc_Release_VC_WX_V4.h"


@interface TopicDetailViewController ()<UIScrollViewDelegate>
@property(nonatomic,strong)UIView *contentView;
@property(nonatomic,strong)TopicDetaillHeadImageView *headImageView;
@property(nonatomic,strong)TopicDetaillHeadInfoView *headInfoView;
@property(nonatomic,strong)TopicDetailUgcTableView *ugcTableView;
@property(nonatomic,strong)UIButton *popBtn;
@property(nonatomic,strong)UIButton *publishBtn;

// 上次的偏移量，为了稳定滑动速率
@property(nonatomic,assign)CGFloat lastOffsetY;
@property(nonatomic,assign)CGFloat headInfoViewDynamicHeight; // tablehead动态高度
@end

@implementation TopicDetailViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.baseNavigationView.hidden = YES;
}
//- (void)viewWillDisappear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.hidden = NO;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    _lastOffsetY = 0.f;
    _headInfoViewDynamicHeight = 0.f;
    [self setNav];
    [self setUI];
    [self requestHttpWithTopicDetailData];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
     _headInfoViewDynamicHeight = self.headInfoView.frame.size.height - self.headInfoView.placeholderImageView.frame.size.height;
}

- (void)setNav {

    [self.view addSubview:self.popBtn];
    [self.popBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(30, 30));
        make.top.equalTo(self.view.mas_top).offset(kStatusBarHeight + 5);
        make.left.equalTo(self.view.mas_left).offset(5);
    }];
    [self.view addSubview:self.publishBtn];
    [self.publishBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 50));
        make.bottom.equalTo(self.view.mas_bottom).offset( -(kBottomSafeHeight + 40) );
        make.right.equalTo(self.view.mas_right).offset(-15);
    }];
}

- (void)setUI {
    self.contentView = [UIView new];
    [self.view addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    // topic image
    self.headImageView.frame = CGRectMake(0, 0, kScreenW, kScreenW / 2);
    [self.contentView addSubview:self.headImageView];
    //tableview
    if (Is_Iphone_X_Series) {
        self.ugcTableView.frame = CGRectMake(0 , 88, kScreenW, kScreenH - (88));
    } else {
        self.ugcTableView.frame = CGRectMake(0 , 64, kScreenW, kScreenH - (64));
    }
    
    [self.contentView addSubview:self.ugcTableView];
    self.ugcTableView.sectionBlock = ^{
        // 最热/最新，通过网络请求切换数据源
        
    };
    // tableviewhead (info)
    
    //临时注释
    self.ugcTableView.tableHeaderView = self.headInfoView;
    
    [self.ugcTableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    
    
    [self.headInfoView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenW);
       // make.height.equalTo(@240);
    }];
    // 获取动态高度
    [self.view layoutIfNeeded];
    _headInfoViewDynamicHeight = self.headInfoView.frame.size.height - self.headInfoView.placeholderImageView.frame.size.height;
  //  NSLog(@"wf topic detail tableviewheader hight : %f",self.headInfoView.frame.size.height);
    
    // nav front
    [self.contentView bringSubviewToFront:self.headImageView];
    [self.view bringSubviewToFront:self.popBtn];
    [self.view bringSubviewToFront:self.publishBtn];
    
}

- (void)dealloc{
    [self.ugcTableView removeObserver:self forKeyPath:@"contentOffset"];
}

#pragma mark - http
- (void)requestHttpWithTopicDetailData {
    [CRBBoxHomeHttp requestTopicDetailWithId:_topicId success:^(NSURLSessionDataTask *task, id responseObject) {
        
        TopicDetailModel *infoModel = (TopicDetailModel *)responseObject;
        
        // head image
        if (infoModel.userSubjectImages) {
            TopicUserSubjectImagesModel *imageModel = infoModel.userSubjectImages[0];
            NSURL *coverUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",RootUrlImage,imageModel.url]];
            [_headImageView.headImageView sd_setImageWithURL:coverUrl placeholderImage:[UIImage imageNamed:@"ucg_img_loding"]];
        } else {
            _headImageView.headImageView.image = [UIImage imageNamed:@"ucg_img_loding"];
        }
        
        // head time
         // 是否过期
        if ([infoModel.period isEqualToString:@"0"]) {
            _headImageView.timeLabel.hidden = YES;
            _publishBtn.hidden = NO;
        }else{
            if (infoModel.expiredStatus ) {
                _headImageView.timeLabel.text = @"已关闭";
                _publishBtn.hidden = YES;
            } else {
                _headImageView.timeLabel.text = [NSString stringWithFormat:@"截止 %@",[Tools timeStampIntoYYMMDD:(infoModel.expiredTime /1000)]];
                _publishBtn.hidden = NO;

            }
        }
 
        
        _headInfoView.titleLabel.text = [NSString stringWithFormat:@"     %@",infoModel.title];
        _headInfoView.contentLabel.text = [NSString stringWithFormat:@"%@",infoModel.note];
        
        // brand
        if (infoModel.userSubjectGoods && infoModel.userSubjectGoods.count > 0) {
            TDBrandModel *model = infoModel.userSubjectGoods[0];
            _headInfoView.brandNameLabel.text = [NSString stringWithFormat:@"%@",model.object.brandInfo.brandName];
            _headInfoView.brandNativeNameLabel.text = [NSString stringWithFormat:@"%@",model.object.brandInfo.brandNameNative];
        } else {
            [_headInfoView.brandView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(_headInfoView.mas_left).offset(15);
                make.right.equalTo(_headInfoView.mas_right).offset(-15);
                make.top.equalTo(_headInfoView.contentLabel.mas_bottom).offset(0);
                make.height.mas_equalTo(0);
                make.bottom.equalTo(_headInfoView.mas_bottom).offset(-21);
            }];
            _headInfoView.brandView.hidden = YES;
            _headInfoView.brandNameLabel.text = @"";
            _headInfoView.brandNativeNameLabel.text = @"";
        }
        
        // 最新最热section view
        _ugcTableView.sectionStr = [NSString stringWithFormat:@"%@人已发布了%@条动态",infoModel.correlationUserCount,infoModel.correlationUgcCount];
        
        // 重新获取contentlabel的subview的动态高度
        [self.view layoutIfNeeded];
        
        
    } fail:^(NSURLSessionDataTask *task, NSError *error, NSString *code, NSString *msg) {
        [Tools showTips:msg];
    }];
}
#pragma mark - action
- (void)popAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
// 发布话题ugc
- (void)publishAction:(id)sender {
    if (kUSER_INFO_MANAGER.userIsLogin) {
        Ugc_Release_VC_WX_V4 * vc= [[Ugc_Release_VC_WX_V4 alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        [Tools pushSinge];
    }
}
#pragma mark - 滑动效果
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    if ([keyPath isEqualToString:@"contentOffset"]) {
        CGPoint newOffset = [change[NSKeyValueChangeNewKey] CGPointValue];
        CGPoint oldOffset = [change[NSKeyValueChangeOldKey] CGPointValue];
       // NSLog(@"wf_ugcTableView.contentInset.top = %f , tbvheadHeight = %f , contentoffset = %f ,lastoffsetY = %f,", _ugcTableView.contentInset.top,_headInfoViewDynamicHeight,newOffset.y,oldOffset.y);
        
//        CGFloat panOffset = newOffset.y - oldOffset.y;
//        NSLog(@"wf panOffset = %f",panOffset);
        
        
            if (newOffset.y > _headInfoViewDynamicHeight) {
                if (newOffset.y - oldOffset.y > 0) {
                    if (Is_Iphone_X_Series) {
                        if (_headImageView.frame.size.height + _headImageView.frame.origin.y <=88) {
                            _headImageView.frame = CGRectMake(0, -((kScreenW / 2) - 88), kScreenW, kScreenW / 2);
                            // y（向上偏移高度） = -（图片高度 - 导航栏高度）
                            return;
                        }
                    } else {
                        if (_headImageView.frame.size.height + _headImageView.frame.origin.y <= 64) {
                            _headImageView.frame = CGRectMake(0, -((kScreenW / 2) - 64), kScreenW, kScreenW / 2);
                            return;
                        }
                    }
                    self.headImageView.frame = CGRectMake(0, -(newOffset.y-_headInfoViewDynamicHeight), kScreenW, kScreenW / 2);
                    
                } else if (newOffset.y - oldOffset.y < 0) {
                    
                    /* headimage.y = -(newOffset.y-_headInfoViewDynamicHeight)
                     headimage.y = -newOffset.y+_headInfoViewDynamicHeight)
                     newOffset.y = _headInfoViewDynamicHeight - headimage.y
                     
                     headimage.y = 64 - _headImageView.frame.size.height
                      headimage.y = 64 - (ksreenW / 2)
                     
                     newOffset.y = _headInfoViewDynamicHeight - ( 64 - (ksreenW / 2)
                     newOffset.y = _headInfoViewDynamicHeight - 64 + (kScreenW / 2);
                     *
                     */
                    if (Is_Iphone_X_Series) {
                        if(newOffset.y >= _headInfoViewDynamicHeight - 88 + (kScreenW / 2)) {
                            return;
                        }

                    } else {
                        if(newOffset.y >= _headInfoViewDynamicHeight - 64 + (kScreenW / 2)) {
                            return;
                        }

                    }
                    self.headImageView.frame = CGRectMake(0, -(newOffset.y-_headInfoViewDynamicHeight), kScreenW, kScreenW / 2);
                }
            }

    }
}

#pragma mark - lazy
- (TopicDetaillHeadImageView *)headImageView {
    if (!_headImageView) {
        _headImageView = [TopicDetaillHeadImageView new];
    }
    return _headImageView;
}

- (TopicDetaillHeadInfoView *)headInfoView {
    if (!_headInfoView) {
        _headInfoView = [TopicDetaillHeadInfoView new];
    }
    return _headInfoView;
}

- (TopicDetailUgcTableView *)ugcTableView {
    if (!_ugcTableView) {
        if (Is_Iphone_X_Series) {
            _ugcTableView = [[TopicDetailUgcTableView alloc]initWithFrame: CGRectMake(0 , kScreenW / 2, kScreenW, kScreenH - (88))];
        } else {
            _ugcTableView = [[TopicDetailUgcTableView alloc]initWithFrame: CGRectMake(0 , kScreenW / 2, kScreenW, kScreenH - (64))];
        }
        _ugcTableView.topicId = _topicId;
        _ugcTableView.indexType = @"2";
    }
    return _ugcTableView;
}
- (UIButton *)popBtn {
    if (!_popBtn) {
        _popBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_popBtn setImage:[UIImage imageNamed:@"pgc_btn_back_white"] forState:UIControlStateNormal];
        [_popBtn addTarget:self action:@selector(popAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _popBtn;
}
- (UIButton *)publishBtn {
    if (!_publishBtn) {
        _publishBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_publishBtn setImage:[UIImage imageNamed:@"话题主页_发布评论"] forState:UIControlStateNormal];
        [_publishBtn addTarget:self action:@selector(publishAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _publishBtn;
}

@end
